/*******************************************************************************
 * Venice Noise Android Application
 * Copyright (C) 2011  Worcester Polytechnic Institute, Wesley Ripley
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; version 2
 * of the License
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 * 
 * If you plan to use or modify any of this code please contact Fabio Carrera (carrera.fabio@gmail.com)
 * Also please attribute any code used in the final product to the developers. 
 * 
 * Author: Wesley Ripley (wripley@wpi.edu) 
 *******************************************************************************/
package org.venicenoise.app;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;

/**
 * The Main activity for the application.
 * @author Wesley Ripley
 * @version 12/15/2011
 */
public class MainActivity extends Activity {
	
	//the id for the refresh map menu item
	private static final int REFRESH_ID = Menu.FIRST;
	//the id for the settings menu item
	private static final int SETTINGS_ID = Menu.FIRST+1;
	
	//the website to load the map from
	private static final String WEBSITE = "http://www.venicenoise.org/map.html";
	//whether or not to refresh the map automatically when returning to this activity
	private boolean autoRefreshMap = true;
	
	private WebView webView;
	//a boolean to determine whether there was an error loading the page
	private boolean loadError = false;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
        AppUtil.setVersionInHeader(this);
        //load web view and set the settings appropriate for viewing our web page
        webView = (WebView) findViewById(R.id.webview);
        webView.setWebViewClient(new ErrorHidingWebClient());
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);//yes javascript
        settings.setBuiltInZoomControls(true);//yes built in zoom control
        settings.setAllowFileAccess(false);//no file access
        settings.setDatabaseEnabled(false);//no databse
        settings.setGeolocationEnabled(true);//yes geolocation
        settings.setUserAgentString(AppUtil.getUserAgentString(this));//tell it to use our own user agent string
        
        webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);//hide the scroll bar
        webView.loadUrl(WEBSITE);
    }
    
    /**Called when the activity is becoming visible to the user.**/
    @Override
    public void onStart()
    {
    	super.onStart();
    	SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(getBaseContext());
    	//get the preference for auto refreshing the map
    	autoRefreshMap = prefs.getBoolean(getString(R.string.pref_autoRefreshKey), true);
    }
    
    /**Called when the activity will start interacting with the user*/
    @Override
    public void onResume()
    {
    	super.onResume();
    	if(autoRefreshMap)
    	{
    		reloadWebView();//reload web page when user returns to this activity
    	}
    }
    
    /**
     * Reload the web page being displayed by the web view
     */
    private void reloadWebView()
    {
    	if(webView != null)
    	{
    		loadError = false;//reset error flag
    		webView.reload();
    	}
    }
    
    /**
     * Function called when the contribute button is clicked 
     * (via the onClick property of the button)
     * @param view
     * 		The view that was clicked causing this method to be called
     */
    public void contributeClicked(View view)
    {
    	Intent recordingActivityIntent = new Intent(view.getContext(), RecordingActivity.class);
        startActivityForResult(recordingActivityIntent, 0);
    }
    
    /**
     * Function called when the queue button is clicked 
     * (via the onClick property of the button)
     * @param view
     * 		The view that was clicked causing this method to be called
     */
    public void queueClicked(View v)
    {
    	Intent queueActivityIntent = new Intent(v.getContext(),SubmissionQueActivity.class);
    	startActivityForResult(queueActivityIntent,0);
    }
    
    /**Initialize the contents of the Activity's standard options menu.*/
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        //add refersh map to menu
        MenuItem refreshItem = menu.add(0, REFRESH_ID, 0, R.string.refresh);
        refreshItem.setIcon(android.R.drawable.ic_menu_rotate);
        //add the settings icon on menu
        MenuItem settingsItem = menu.add(0,SETTINGS_ID,0,R.string.preferences);
        settingsItem.setIcon(android.R.drawable.ic_menu_preferences);
        return true;
    }

    /**Called when a panel's menu item has been selected by the user.*/
    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
            case REFRESH_ID:
            	//if the user clicks refresh, refresh the map
            	reloadWebView();
                return true;
            case SETTINGS_ID:
            	//if the user clicks preferences open preferences
            	openPreferences();
            	return true;
        }
        return super.onMenuItemSelected(featureId, item);
    }
    
    /**
     * Starts the activity to deal with preferences
     */
    private void openPreferences()
    {
    	Intent settingsActivity = new Intent(this,PreferencesActivity.class);
    	startActivity(settingsActivity);
    }
    
    /**
     * A WebViewClient that handles when there is an error loading the page
     * and when the page finishes loading in order to hide errors from the user
     * 
     * @author Wesley Ripley
     * @version 12/5/2011
     */
    private class ErrorHidingWebClient extends WebViewClient
    {	
    	/**Called when there is a error with the WebView*/
    	@Override
    	public void onReceivedError (WebView view, int errorCode, String description, String failingUrl)
    	{
    		loadError = true; //set the error flag to true
    		mapImageVisibility(true);//make the static map visible instead of the WebView
    	}
    	
    	/**Called when the page finishes loading */
    	@Override
    	public void onPageFinished (WebView view, String url)
    	{
    		if(!loadError)//if there wasn't an error
    		{
    			mapImageVisibility(false);//make the WebView visible and hide the static map
    		}
    	}
    	
    	@Override
    	public boolean shouldOverrideUrlLoading (WebView view, String url)
    	{
    		if(WEBSITE.equals(url))
    		{
    			return false;
    		}
    		return true;
    	}
    }
    
    /**
     * Toggle the visibility of the static map used when the web map can't load.
     * The WebView and the static map are never visible at the same time
     * @param visible
     * 		true if the static map should be visible and the WebView should not be,
     * 		false if the static map should be hidden and the WebView should be shown.
     */
    private void mapImageVisibility(boolean visible)
    {
    	ImageView mapImage = (ImageView)findViewById(R.id.mapImageView);
    	if(webView == null || mapImage == null)
    	{
    		return;
    	}
    	if(visible)
    	{
    		mapImage.setVisibility(View.VISIBLE);
    		webView.setVisibility(View.GONE);
    	}
    	else
    	{
    		mapImage.setVisibility(View.GONE);
    		webView.setVisibility(View.VISIBLE);
    	}
    }

}
